from datetime import datetime

from flask import Flask
from flask_sqlalchemy import SQLAlchemy


app = Flask(__name__)

# 配置数据库
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@127.0.0.1:3306/blog"
# 如果设置成 True (默认情况)，Flask-SQLAlchemy 将会追踪对象的修改并且发送信号。
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

# 绑定app至SQLAlchemy
db = SQLAlchemy(app)



# 会员模型
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50))
    password = db.Column(db.String(50))
    phone = db.Column(db.String(11))
    sex = db.Column(db.String(1))
    info = db.Column(db.String(255))
    status = db.Column(db.Integer,default=0)
    face = db.Column(db.String(100))
    posts = db.relationship('Posts',backref="user",cascade="all, delete,delete-orphan")
    comments = db.relationship('Comments',backref="usercs",cascade="all, delete,delete-orphan")
    addtime = db.Column(db.DateTime,default=datetime.now)

    # 密码加密方法
    @classmethod
    def MD5password(cls,password):
        import hashlib
        m2 = hashlib.md5()
        m2.update(password.encode("utf-8"))
        return m2.hexdigest()

    # 密码检测
    def CheckPassword(self,password):
        import hashlib
        m2 = hashlib.md5()
        m2.update(password.encode("utf-8"))
        password = m2.hexdigest()

        # 判断加密后的密码和数据库中的当前密码是否一样
        if self.password == password:
            return True
        else:
            return False



# 标签文章关系
tags = db.Table('post_tag',
    db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')),
    db.Column('post_id', db.Integer, db.ForeignKey('posts.id'))
)

#文章
class Posts(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    uid = db.Column(db.Integer, db.ForeignKey('user.id'))
    context = db.Column(db.Text)
    clicknum  = db.Column(db.Integer,default=0)
    status = db.Column(db.Integer,default=0)
    tags = db.relationship('Tags',secondary=tags,backref='Posts')
    comments = db.relationship('Comments',backref="postcs",cascade="all, delete,delete-orphan")
    addtime = db.Column(db.DateTime,default=datetime.now)

    def __repr__(self):
        return self.title

#标签
class Tags(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    def __repr__(self):
        return self.name


# 评论模型
class Comments(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    # 是否回复 0 楼主,1普通评论,2回复
    reply = db.Column(db.Integer)
    # 如果是回复,则记录评论的id
    cid = db.Column(db.Integer)
    context = db.Column(db.String(255))
    status = db.Column(db.Integer,default=0)
    addtime = db.Column(db.DateTime,default=datetime.now)


if __name__ == "__main__":

    db.create_all()

    # obs = User.query.all()
    # print(obs)
